package me.fanchaoo.web.service.impl;

import lombok.extern.slf4j.Slf4j;
import me.fanchaoo.dbo.*;
import me.fanchaoo.enums.EnumFollowTargetType;
import me.fanchaoo.enums.EnumFriendType;
import me.fanchaoo.enums.EnumGender;
import me.fanchaoo.util.BeanCopyUtils;
import me.fanchaoo.util.PageUtils;
import me.fanchaoo.util.UserContext;
import me.fanchaoo.web.dao.mapper.*;
import me.fanchaoo.web.dto.LoginUserDTO;
import me.fanchaoo.web.dto.UserDTO;
import me.fanchaoo.web.dto.UserSettingDTO;
import me.fanchaoo.web.request.*;
import me.fanchaoo.web.response.BaseResponse;
import me.fanchaoo.web.service.UserService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private UserQueryMapper userQueryMapper;
    @Resource
    private RegionCityQueryMapper regionCityQueryMapper;
    @Resource
    private RegionProvinceQueryMapper regionProvinceQueryMapper;
    @Resource
    private UserSettingQueryMapper userSettingQueryMapper;

    @Resource
    private ArtistQueryMapper artistQueryMapper;
    @Resource
    private FollowRelationQueryMapper followRelationQueryMapper;
    @Resource
    private UserSettingMapper userSettingMapper;

    @Override
    public BaseResponse<UserDTO> getUserInfo(GetUserInfoRequest request) {
        BaseResponse<UserDTO> response = new BaseResponse<>();
        LoginUserDTO loginUser = UserContext.getLoginUser();
        Long userId = loginUser.getUserId();
        Long artistId = loginUser.getArtistId();

        if (request.getUserId() != null) {
            userId = request.getUserId();
        }

        UserDBO userDBO = userQueryMapper.getById(artistId, userId);
        UserDTO dto = BeanCopyUtils.copy(userDBO, UserDTO.class);
        response.setBody(dto);
        return response;
    }
    @Override
    public  BaseResponse<UserSettingDTO>  queryUserSetting(QueryOtherUserRequest request){
        BaseResponse<UserSettingDTO> response = new BaseResponse<>();
        LoginUserDTO loginUser = UserContext.getLoginUser();
        Long userId = loginUser.getUserId();
        Long artistId = loginUser.getArtistId();
        if (request.getUserId() != null) {
            userId=request.getUserId();
        }
        UserSettingDBO userSettingDBOQuery =  userSettingQueryMapper.getByUserId(artistId,userId);
        UserSettingDTO dto = BeanCopyUtils.copy(userSettingDBOQuery, UserSettingDTO.class);
        response.setBody(dto);
        return response;
    }


    @Override
    public BaseResponse<List<UserDTO>> queryUsers(QueryUsersRequest request) {
        BaseResponse<List<UserDTO>> response = new BaseResponse<>();


        // 从header获取
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest requestData = servletRequestAttributes.getRequest();
        String token = requestData.getHeader("token");
        Long artistId;
        Long userId;
        if (org.apache.commons.lang3.StringUtils.isBlank(token)) {
            ArtistDBO artistDBO = artistQueryMapper.getByRandomKey(request.getRandomKey());
            artistId =artistDBO.getId();
            userId= -1L;
        }else {
            LoginUserDTO loginUser = UserContext.getLoginUser();
            artistId = loginUser.getArtistId();
            userId = loginUser.getUserId();
        }

        Long reqUserId=request.getUserId();
        Integer pageNo = request.getPageNo();
        String keyword= request.getKeyword();
        Integer pageSize = request.getPageSize();
        int start = PageUtils.getStart(pageNo, pageSize);
        List<UserDBO> userDBOList = userQueryMapper.queryByUserName(artistId,keyword,start,pageSize,reqUserId);
            if (CollectionUtils.isEmpty(userDBOList)) {
                response.setBody(new ArrayList<>());
                return response;
            }
            List<Long>  userIdList =userDBOList.stream().map(UserDBO::getId).collect(Collectors.toList());
            List<FollowRelationDBO> followDBOList = followRelationQueryMapper.queryByUserTargetTypeTargetIds(artistId, userId, EnumFollowTargetType.USER.getValue(), userIdList);
            Set<Long> followUserIdSet = followDBOList.stream().map(FollowRelationDBO::getTargetId).collect(Collectors.toSet());
            List<UserDTO> userDTOList = BeanCopyUtils.copy(userDBOList, UserDTO.class);
            userDTOList.forEach(userDTO -> {
                if (followUserIdSet.contains(userDTO.getId())) {
                    userDTO.setHasFollowed(true);
                } else {
                    userDTO.setHasFollowed(false);
                }
            });
            response.setBody(userDTOList);
        return response;
    }

    @Override
    public BaseResponse updateUserInfo(UpdateUserInfoRequest request) {
        BaseResponse response = new BaseResponse<>();
        LoginUserDTO loginUser = UserContext.getLoginUser();
        Long userId = loginUser.getUserId();
        Long artistId = loginUser.getArtistId();

        UserDBO dbo = BeanCopyUtils.copy(request, UserDBO.class);
        dbo.setArtistId(artistId);
        dbo.setId(userId);

        EnumGender gender = request.getGender();
        if (Objects.nonNull(gender)) {
            dbo.setGender(gender.getValue());
        }

        String cityId = request.getCityId();
        if (StringUtils.isNotBlank(cityId)) {
            RegionCityDBO city = regionCityQueryMapper.selectByPrimaryKey(cityId);
            if (Objects.nonNull(city)) {
                String provinceId = city.getProvinceId();
                RegionProvinceDBO province = regionProvinceQueryMapper.selectByPrimaryKey(provinceId);
                if (Objects.nonNull(province)) {
                    dbo.setProvince(province.getName());
                    dbo.setCity(city.getName());
                }
            }
        }
        String cityStringArr= request.getCityStringArr();
        if (StringUtils.isNotBlank(cityStringArr)) {
            String[] strArr= cityStringArr.split("-");
            dbo.setProvince(strArr[0]);
            dbo.setCity(strArr[1]);
        }

        userMapper.updateByPrimaryKeySelective(dbo);
        return response;
    }

    @Override
    public BaseResponse updateUserSetting(UpdateUserSettingRequest request) {
        BaseResponse response = new BaseResponse<>();
        LoginUserDTO loginUser = UserContext.getLoginUser();
        Long userId = loginUser.getUserId();
        Long artistId = loginUser.getArtistId();

        UserSettingDBO dbo = BeanCopyUtils.copy(request, UserSettingDBO.class);
        dbo.setArtistId(artistId);
        dbo.setUserId(userId);
        userSettingMapper.updateByPrimaryKeySelective(dbo);
        return response;
    }
}
